<?php
class Access_Model_Access extends Zend_Db_Table_Abstract
{
    public function getList($roleIdSelect = null, $moduleList)
    {
        try {
            if($roleIdSelect == null) {
                throw new Exception('Not role id');
            }
            
            $query = $this->_db
                          ->select()
                          ->from('access_rules',
                                 array(
                                     'rules_id',
                                     'rules_resource',
                                     'rules_privileg',
                                 )
                            )
                          ->where('rules_roles_id' . ' = ?', $roleIdSelect);
            $accessList = $this->_db->fetchAll($query);
            if(empty($accessList)) {
                return $moduleList;
            }
            // add access of privileges
            foreach ($accessList as $accessElement) {

                if($accessElement['rules_resource'] == 'all') {
                    return 'admin';
                }
                
                $resource = explode('_', $accessElement['rules_resource']);
                $module = $resource[0];
                $controller = $resource[1];
                $privileges = explode(',', $accessElement['rules_privileg']);

                foreach ($privileges as $privileg) {
                    $moduleList[$module]['access'][$controller][$privileg] = 'allow';
                }
            }
            return $moduleList;
        } catch (Exception $e) {
            error_log($e);
            return FALSE;
        }
        
    }
    public function deleteRules($roleIdSelect = null) {
        try {
            if($roleIdSelect == null) {
                throw new Exception('Not role id');
            }

            $query = $this->_db
                          ->delete('access_rules', array('rules_roles_id = ?' => $roleIdSelect));
        } catch (Exception $e) {
            error_log($e);
            return FALSE;
        }
    }

    public function insertRules($roleIdSelect = null, array $data) {
        
        if(isset($data['administrator'])) {
            $data = array( 'rules_roles_id' => $roleIdSelect,
		    'rules_resource' => 'all',
		    'rules_privileg' => 'all');
            $this->_db->insert('access_rules', $data);
        } else {
            foreach ($data as $app => $controller) {

                foreach ($controller as $controllerName => $action) {

                    $data = array(
                        'rules_roles_id' => $roleIdSelect,
                        'rules_resource' => $app . '_' . $controllerName,
                        'rules_privileg' => implode(',', $action));
                    $this->_db->insert('access_rules', $data);
                }
            }
        }
    }
}